/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rhythm.commons.regx;

import com.rhythm.base.Nulls;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Michael J. Lee
 */
public class RegX {

   
    /**
     * Returns if the given String contains any instance of the pattern.  
     * <br/>
     * Examples...
     * <pre>
     * contains("  12345   ", "\\d{5}")                 = true
     * contains("\t xyz@hotmail.com", ".+@.+\\.[a-z]+") = true
     * contains("4", "([a-z])")                         = false
     * contains("4", "\\d")                             = true
     * </pre>
     * 
     * @param str source
     * @param pattern the pattern
     * @return True if given String contains any maches of the given pattern.
     * @see Matcher
     * @see Pattern
     * @throws NullPointerException if str or pattern are null
     */
    public static synchronized boolean contains(String str, String pattern) {
        Nulls.failIfNull(str, "Cannot check a null string for a pattern.");
        Nulls.failIfNull(str, "Cannot check a string with a null pattern.");

        Pattern p = Pattern.compile(pattern);
        return p.matcher(str).find();
    }

    /**
     * Returns all the found instances of a given valid regual expression pattern.
     * 
     * @param str the source to search
     * @param regexPattern a valid regEx pattern
     * @return A new <code>String</code> array of all the found instance of the 
     * pattern.
     * 
     * @see Matcher
     * @see Pattern
     * @throws NullPointerException if str or pattern are null
     */
    public static synchronized String[] findAll(String str, String regexPattern) {
        
        //TODO: better javaDoc
        Nulls.failIfNull(str, "Cannot check a null string for a pattern.");
        Nulls.failIfNull(str, "Cannot check a string with a null pattern.");
        
        Pattern pattern = Pattern.compile(regexPattern);

        Matcher matcher = pattern.matcher(str).
                useAnchoringBounds(false).
                useTransparentBounds(true);
        
        List<String> strings = new ArrayList<String>();

        while (matcher.find()) {
            strings.add(matcher.group());
        }

        return strings.toArray(new String[strings.size()]);



    }
}
